<!-- 查看审批呈批件 -->
<template>
  <div class="app-container-box" :style="height">
    <div class="app-container" style="padding: 10px;">
      <!-- 呈批件内容 -->
      <div class="post-handle-content">
        <div style="margin-left: 40px;"><h2>呈批件内容</h2></div>
        <el-row>
          <el-col :span="12">
            <el-form ref="form" :model="form" class="work-search-form" :rules="rules" label-width="80px">
              <el-form-item label="标题" prop="title">
                <el-input v-model="form.title" placeholder="请输入标题" :disabled="disabled" />
              </el-form-item>
              <el-form-item label="编号" prop="number">
                <el-input v-model="form.number" placeholder="请输入编号" :disabled="disabled" />
              </el-form-item>
              <el-form-item label="缓急程度" prop="pressing">
                <el-select v-model="form.pressing" placeholder="请选择缓急程度" :disabled="disabled">
                  <el-option
                    v-for="dict in degreeOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="密级" prop="security">
                <el-select v-model="form.security" placeholder="请选择密级" :disabled="disabled">
                  <el-option
                    v-for="dict in secretLevelOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="提交部门">
                <el-input v-model="form.applyDepartmentName" placeholder="" :disabled="true" />
              </el-form-item>
              <el-form-item label="提交人">
                <el-input v-model="form.applyUser" placeholder="" :disabled="true" />
              </el-form-item>
              <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="form.remark" placeholder="请填写备注" :disabled="disabled" />
              </el-form-item>
              <el-form-item label="附件">
                <template v-if="form.fileList != undefined">
                  <template v-if="form.fileList.length>0">
                    <el-button type="primary" @click="downloadFile('all')" size="mini">全部下载</el-button>
                    <el-row v-for="(item,index) in form.fileList" :key="index">
                      <el-col :span="22" :title="item.name" class="text-hidden">{{item.name}}</el-col>
                      <el-col :span="2" class="text-download-icon"><i class="el-icon-download" @click="downloadFile('single',item)" style="cursor: pointer;"></i></el-col>
                    </el-row>
                  </template>
                </template>
              </el-form-item>
              <!-- <el-form-item label="接收人">
                <el-tree
                  :data="menuOptions"
                  show-checkbox
                  ref="menu"
                  node-key="id"
                  empty-text="加载中，请稍后"
                  :props="defaultProps"
                ></el-tree>
                <div slot="tip" class="el-upload__tip">可多选，未指定为对所有人公开</div>
              </el-form-item> -->
            </el-form>
          </el-col>
        </el-row>
      </div>
      <div style="margin: 10px 0px;"></div>
      <!-- 意见详情 -->
      <div class="post-handle-content">
        <div style="margin-left: 40px;"><h2>意见详情</h2></div>
        <div style="margin-left: 40px;" class="time-axis">
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in historicList"
              :key="index">
                <div class="timeline-name">{{ activity.activityName }}
                <span style="display: inline-block;color: #bebebe;margin-left: 10px;">{{datetime_format(activity.startTime)}}</span></div>
                <div style="height: 5px;"></div>
                <div class="timeline-content">{{ activity.assigneeName }}
                <span style="display: inline-block;margin-left: 10px;">{{activity.comment}}</span></div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
      <div style="margin: 10px 0px;"></div>
      <!-- 处理 -->
      <template v-if="params.isApproval">
        <div class="post-handle-content">
          <div style="margin-left: 40px;"><h2>处理</h2></div>
          <el-row>
            <el-col :span="12">
              <el-form ref="handleForm" :model="handleForm" :rules="handleRules" label-width="80px">
                <el-form-item label="处理意见" prop="result">
                  <el-radio-group v-model="handleForm.result" @change="handleResult">
                    <el-radio :label="1" border>同意</el-radio>
                    <el-radio type="danger" :label="2" border>退回</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="编辑意见" prop="comment">
                  <el-input type="textarea" v-model="handleForm.comment" placeholder="请填写编辑意见" />
                </el-form-item>
                <template v-if="form.isTransaction != 3 && form.isTransaction != 4">
                  <el-form-item label="下一节点" prop="dispose">
                    <template v-if="nextListdispose && nextListdispose.length > 0">
                      <el-radio-group v-model="handleForm.dispose" class="new-el-radio">
                        <el-radio v-for="(item,index) in nextListdispose" :key="index" :label="item.code" border>{{item.name}}</el-radio>
                      </el-radio-group>
                    </template>
                    <template v-else><span>当前没有可选择的节点，暂不能提交</span></template>
                  </el-form-item>
                  <template v-if="(handleForm.status==1||handleForm.status==2) && (handleForm.dispose>=0)">
                    <el-form-item label="选择人员" prop="ids">
                      <el-select v-model="handleForm.ids" placeholder="请选择人员" :multiple="handleForm.status==1?true:false">
                        <el-option
                          v-for="dict in userList"
                          :key="dict.user_id"
                          :label="dict.user_name"
                          :value="dict.user_id"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </template>
              </el-form>
            </el-col>
          </el-row>
          <div slot="footer" class="dialog-footer" style="text-align:center">
            <el-button type="primary" @click="printTable" v-hasPermi="['system:batch:print']">打 印</el-button>
            <el-button type="primary" :loading="submitLoading" @click="submitForm('3')">提 交</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </div>
      </template>
      <template v-else>
        <div class="post-handle-content">
          <div slot="footer" class="dialog-footer" style="text-align:center">
            <el-button type="primary" @click="printTable" v-hasPermi="['system:batch:print']">打 印</el-button>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
  import { getUserList } from "@/api/system/postProcessSheetManage";
  import {addAnnouncement, detailsApprovalDoc, handleApprovalDoc,
   updateAnnouncement, submitProcessModel, cbrSubmitProcessModel,fileSubmitProcessModel } from "@/api/system/approvalDocManage";
  import Editor from '@/components/Editor';
  import { getToken } from "@/utils/auth";
  import { fileUploadParams } from "@/utils/ruoyi"

  export default {
    name: "ApprovalDoc",
    components: {
      Editor
    },
    data() {
      return {
        height: "max-height:"+((document.documentElement.clientHeight || document.body.clientHeight)-110)+"px;overflow-y:auto",
        form: {},
        fileUploadParams: fileUploadParams(),
        userInfo: JSON.parse(this.$store.getters.userInfo),
        // 缓急程度数据字典
        degreeOptions: [],
        // 密级数据字典
        secretLevelOptions: [],
        //部门列表
        deptList: [],
        //用户列表
        userList: [],
        //用户列表
        // 部门列表
        menuOptions: [],
        defaultProps: {
          children: "children",
          label: "label"
        },
        params: {
          isApproval: false,
        },
        disabled: true,
        // 表单校验
        rules: {
          // title: [
          //   { required: true, message: "标题不能为空", trigger: "blur" }
          // ],
          // announcementType: [
          //   { required: true, message: "类型不能为空", trigger: "blur" }
          // ],
          // announcementContent: [
          //   { required: true, message: "内容不能为空", trigger: "blur" }
          // ],
        },
        upload: {
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/common/upload",
          // 上传的文件列表
          fileList: []
        },
        // 处理表单
        handleForm: {
          result: 1,   //同意还是驳回
          dispose: undefined,  //下一节点的code
          taskId: undefined,
          comment: undefined,  //编辑意见
          jiedianList: undefined,
          ids: '',  //选择人员
          status: undefined, //状态
        },
        submitLoading: false,
        listdispose: [],
        nextListdispose: [],
        handleRules: {
          result: [{ required:true, message:'请选择处理意见', trigger:'change' }],
          comment: [{ required:true, message:'请填写编辑意见', trigger:'blur' }],
          dispose: [{ required:true, message:'当前暂无可选节点', trigger:'change' }],
          ids: [{ required:true, message:'请选择人员', trigger:'change' }],
        },
        historicList: [],
        //时间轴数据
        activities: [
          {
            content: '默认样式的节点',
            timestamp: '2018-04-03 20:46',
            color: '#0bbd87'
          },
        ],
      }
    },
    created() {
      if(!this.$route.params || !this.$route.params.docId){
        this.msgError('请从列表中进入详情')
      }else if(this.$route.params && this.$route.params.docId>0 && this.$route.params.isApproval == true){
        this.$route.meta.title = '处理审批件'
        this.$store.state.tagsView.visitedViews[this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path)].title = '处理审批件'
      }else if(this.$route.params && this.$route.params.docId>0 && this.$route.params.isApproval == false){
        this.$route.meta.title = '查看审批件'
        this.$store.state.tagsView.visitedViews[this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path)].title = '查看审批件'
      }
      this.reset();
      const id = this.$route.params && this.$route.params.docId;
      const taskId = this.$route.params && this.$route.params.taskId;
      this.params = this.$route.params;
      if(id && id > 0){
        //this.getApprovalDocList(taskId)
        //获取详情
        detailsApprovalDoc({id:id}).then((res)=>{
          this.form = res.data
          //获取文件列表数据
          this.$nextTick(() => {
            const arr = [];
            if (this.form.attachmentName != null){
              var attachmentName = this.form.attachmentName.split(",");
              var attachmentUrl = this.form.attachmentUrl.split(",");
              var attachmentPath = this.form.attachmentPath.split(",");
              for (var k=0;k<attachmentName.length;k++){
                arr.push({
                  name:attachmentName[k],
                  response:{
                    fileName:attachmentPath[k],
                    url:attachmentUrl[k],
                  }
                });
              }
            }
            this.upload.fileList=arr;
            this.form.fileList=arr;
          });
          //获取审批列表数据
          this.getApprovalDocList(this.form.task ? this.form.task : taskId)
          console.log(this.form)
        })
      }
      this.getDicts("degree_urgency").then(response => {
        this.degreeOptions = response.data;
      });
      this.getDicts("secret_level").then(response => {
        this.secretLevelOptions = response.data;
      });
      this.getUserList()
      //获取当前用户的组织数据权限
      //this.getMenuTreeselect();
      // if (row!=null && row!=undefined && row!=''){
      //   this.form = row;
      //   this.form.announcementType = ''+this.form.announcementType+'';
      //   this.$nextTick(() => {
      //     const arr = [];
      //     if (this.form.receiveUserId != null){
      //       var userids = this.form.receiveUserId.split(",");
      //       for (var k=0;k<userids.length;k++){
      //         arr.push(parseInt(userids[k]));
      //       }
      //     }
      //     this.$refs.menu.setCheckedKeys(userids);//获取已经设置的资源后渲染
      //   });
      // }
    },
    methods: {
      //获取用户列表
      getUserList(){
        getUserList().then((res)=>{
          if(res.code == 200){
            this.userList = res.data
          }
        })
      },
      //处理意见触发事件
      handleResult(val){
        this.getNextListdispose(val)
      },
      // 获取handleApprovalDoc
      getApprovalDocList(taskId){
        var params = {
          taskId: taskId ? taskId : '',
          id: this.form.id,
        }
        handleApprovalDoc(params).then((res)=>{
          console.log(res)
          if(res.code == 200){
            this.listdispose = res.data.listdispose
            this.handleForm.taskId = res.data.taskId
            this.handleForm.status = res.data.status
            this.historicList = res.data.historicList
            this.getNextListdispose(this.handleForm.result)
          }
        })
      },
      // 获取下一节点列表数据
      getNextListdispose(val){
        var arr = []
        this.handleForm.dispose = undefined
        this.handleForm.comment = undefined
        this.handleForm.ids = ''
        this.$nextTick(()=>{
          if(this.$refs.handleForm != undefined){
            this.$refs['handleForm'].clearValidate()
          }
        })
        if(val == 1){
          //同意
          if(this.listdispose && this.listdispose.length>0){
            for(var i=0;i<this.listdispose.length;i++){
              if(this.listdispose[i].code >= 0){
                arr.push(this.listdispose[i])
              }
            }
            this.nextListdispose = arr
            if(this.nextListdispose && this.nextListdispose.length>0){
              this.handleForm.dispose = this.nextListdispose[0].code
            }
          }
        }else if(val == 2){
          //驳回
          for(var i=0;i<this.listdispose.length;i++){
            if(this.listdispose[i].code < 0){
              arr.push(this.listdispose[i])
            }
          }
          this.nextListdispose = arr
          if(this.nextListdispose && this.nextListdispose.length>0){
            this.handleForm.dispose = this.nextListdispose[0].code
          }
        }
      },
      // 表单重置
      reset() {
        if (this.$refs.menu != undefined) {
          this.$refs.menu.setCheckedKeys([]);
        }
        this.form = {
          title: undefined,
          number: undefined,
          pressing: undefined,
          security: undefined,
          remark: undefined,
          fileList: [],
        };
        this.upload.fileList = [];
        this.resetForm("form");
      },
      // 取消按钮
      cancel() {
        this.$router.go(-1);// 返回
        //关闭子页面
        this.$store.state.tagsView.visitedViews.splice(this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path), 1);
        var view = {
          name: 'ApprovalDocManage',
        }
        this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {
          this.$router.push({
            name: 'ApprovalDocManage'
          });
        })
      },
      /** 提交按钮 */
      submitForm:function(statu) {
        this.$refs['handleForm'].validate(valid => {
          if(valid){
            this.submitLoading = true
            var params = Object.assign({}, this.handleForm)
            if(params.ids != null && params.ids != undefined){
              if(typeof(params.ids) == 'object' && params.ids.length>0){
                params.ids = params.ids.join(',')
              }
            }
            if(this.form.isTransaction == 3){
              params['id'] = this.form.id
              cbrSubmitProcessModel(params).then((res)=>{
                this.submitLoading = false
                if(res.code == 200){
                  this.msgSuccess('操作成功')
                  this.cancel()
                }
              }).catch(()=>{
                this.submitLoading = false
              })
            }else if(this.form.isTransaction == 4){
              params['id'] = this.form.id
              fileSubmitProcessModel(params).then((res)=>{
                this.submitLoading = false
                if(res.code == 200){
                  this.msgSuccess('操作成功')
                  this.cancel()
                }
              }).catch(()=>{
                this.submitLoading = false
              })
            }else{
              submitProcessModel(params).then((res)=>{
                this.submitLoading = false
                if(res.code == 200){
                  this.msgSuccess('操作成功')
                  this.cancel()
                }
              }).catch(()=>{
                this.submitLoading = false
              })
            }
          }
        })
        // this.$refs["form"].validate(valid => {
        //   if (valid) {
        //     if (this.form.announcementId != null) {
        //       this.form.status = statu;
        //       this.form.menuIds = this.getMenuAllCheckedKeys();
        //       updateAnnouncement(this.form).then(response => {
        //         if (response.code === 200) {
        //           this.msgSuccess("修改成功");
        //           this.cancel();
        //         }
        //       });
        //     } else {
        //       this.form.status = statu;
        //       this.form.menuIds = this.getMenuAllCheckedKeys();
        //       addAnnouncement(this.form).then(response => {
        //         if (response.code === 200) {
        //           this.msgSuccess("新增成功");
        //           this.cancel();
        //         }
        //       });
        //     }
        //   }
        // });
      },
      // 跳转到打印单页面
      printTable(){
        this.$store.dispatch('tagsView/delView', {'name':'PrintApprovalDoc'}).then(({ visitedViews }) => {
          this.$router.push({
            name: 'PrintApprovalDoc',
            params:{
              id: this.form.id
            }
          });
        })
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.msgSuccess(response.msg);
        this.$alert(response.url, '视频地址', {
          dangerouslyUseHTMLString: true
        });
      },
      // 下载所有文件
      downloadFile(status, row){
        if(status == 'all'){
          //下载全部
          if(this.form.fileList && this.form.fileList.length>0){
            for(var i=0;i<this.form.fileList.length;i++){
              if(this.form.fileList[i].response.url){
                const a = document.createElement('a');
                a.setAttribute('download', this.form.fileList[i].name);
                a.setAttribute('title', this.form.fileList[i].name);
                a.setAttribute('target', '_blank');
                a.setAttribute('href', this.form.fileList[i].response.url);
                a.click();
              }
            }
          }else{
            this.msgError('当前没有可下载的文件')
          }
        }else if(status == 'single'){
          //下载单个
          const a = document.createElement('a');
          a.setAttribute('download', row.name);
          a.setAttribute('title', row.name);
          a.setAttribute('target', '_blank');
          a.setAttribute('href', row.response.url);
          a.click();
        }
      },
      // 附件上传成功处理
      annexSuccess(response, file, fileList) {
        this.form.fileList=fileList
      },
      // 附件上传失败处理
      annexRemove(file, fileList) {
        this.form.fileList=fileList
      },
      /** 查询菜单树结构 */
      getMenuTreeselect() {
        treeselect().then(response => {
          this.menuOptions = response.data;
        });
      },
      // 所有人员节点数据
      getMenuAllCheckedKeys() {
        // 目前被选中的菜单节点
        let checkedKeys = this.$refs.menu.getHalfCheckedKeys();
        // 半选中的菜单节点
        let halfCheckedKeys = this.$refs.menu.getCheckedKeys();
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        return checkedKeys;
      },
      // 类型字典翻译
      typeFormat(row, column) {
        return this.selectDictLabel(this.typeOptions, row.announcementType);
      },
    }
  }
</script>
